#region Using References

using System;
using Beaker.OpenCube.Mapping;

#endregion

namespace Beaker.OpenCube.Game.Converters
{
	/// <summary>
	/// Converter to convert between NBT game ticks and .NET TimeSpan
	/// </summary>
	public class GameTicksTimeSpanConverter
		: IValueConverter
	{
		/// <summary>
		/// The tick multiplier to get from one game tick to one .NET time tick
		/// </summary>
		public const long TickMultiplier = TimeSpan.TicksPerDay / 24000;

		/// <summary>
		/// Convert from NBT game ticks to a local .NET TimeSpan.
		/// </summary>
		/// <param name="nbtValue">The NBT game ticks value to convert to a local TimeSpan.</param>
		/// <returns>
		/// A local TimeSpan.
		/// </returns>
		/// <exception cref="System.InvalidOperationException">Can only convert long (game ticks) to TimeSpan</exception>
		public object FromNbtToLocal( object nbtValue )
		{
			if( nbtValue is long )
			{
				var gameTick = (long)nbtValue;
				return TimeSpan.FromTicks( gameTick * TickMultiplier );
			}
			else if( nbtValue is int )
			{
				long gameTick = (int)nbtValue;
				return TimeSpan.FromTicks( gameTick * TickMultiplier );
			}
			else if( nbtValue is short )
			{
				long gameTick = (short)nbtValue;
				return TimeSpan.FromTicks( gameTick * TickMultiplier );
			}

			throw new InvalidOperationException( "Can only convert short, int or long (game ticks) to TimeSpan" );
		}

		/// <summary>
		/// Convert from local .NET TimeSpan to a NBT game ticks value.
		/// </summary>
		/// <param name="localValue">The local TimeSpan to convert to a NBT game ticks value.</param>
		/// <returns>
		/// A NBT game ticks value.
		/// </returns>
		/// <exception cref="System.InvalidOperationException">Can only convert TimeSpan to long (game ticks)</exception>
		public object FromLocalToNbt( object localValue, Type targetType )
		{
			if( localValue is TimeSpan )
			{
				var gameTime = (TimeSpan)localValue;
				return gameTime.Ticks / TickMultiplier;
			}

			throw new InvalidOperationException( "Can only convert TimeSpan to long (game ticks)" );
		}
	}
}